package com.backflash.client.screens;

import com.backflash.client.BackFlash;
import com.backflash.client.BackFlashService;
import com.backflash.client.BackFlashServiceAsync;
import com.backflash.client.bean.User;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class LoginScreen extends Composite {

	private TextBox txtLogin=new TextBox();
	private PasswordTextBox txtPassword=new PasswordTextBox();
	private Label lblError=new Label();

	public LoginScreen() {
		
		Grid grid = new Grid(4, 2);
		grid.setStyleName("grid");
		grid.setWidget(0,1, lblError);
		Label label = new Label("Username");
		grid.setWidget(1,0, label);
		grid.setWidget(1,1, txtLogin);
		grid.setWidget(2,0, new Label("Password"));
		grid.setWidget(2,1, txtPassword);
		Button btnLogin=new Button("login");
		grid.setWidget(3,1, btnLogin );
		
		btnLogin.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event){
				checkLogin(txtLogin.getText(),txtPassword.getText());
			}
		});
		
		initWidget(grid);
	}
	private BackFlashServiceAsync getService() {
		BackFlashServiceAsync svc = (BackFlashServiceAsync) GWT.create(BackFlashService.class);
		ServiceDefTarget endpoint = (ServiceDefTarget) svc;
		endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() + "BackFlashService");

		return svc;
	}

	/**
	 * This method is called when the button is clicked
	 */
	private void checkLogin(String userName,String password)    {
		System.out.println("Checking login for "+userName);

		/**
		 * Async call to the server to check for login
		 */
		AsyncCallback callback = new AsyncCallback() {
			@Override
			public void onSuccess(Object result) {
				User user = (User) result;
				if (user != null) {
					setErrorText("");
					BackFlash.get().setStartScreen();
				} else {
					setErrorText("Invalid UserName or Password");
				}
			}
			@Override
			public void onFailure(Throwable ex) {
				setErrorText("Error "+ex.getMessage());
			}
		};
		getService().checkLogin(userName, password,callback);
	}
	private void setErrorText(String errorMessage)	{
		lblError.setText(errorMessage);
	}
}
